//获取应用实例
import { getOrderList, cancelOrder } from '../../service/order.js';
const app = getApp()

Page({
  data: {
    navIndex:0,
    orderList:[
      // page页码  len 当前数据长度
      // all: 判断是否为全部数据 false可继续请求 true 不可继续请求
      {list: [],page:1,len:0,all:false}, // 全部订单 
      { list: [], page: 1, len: 0, all: false}, // 进行中
      { list: [], page: 1, len: 0, all: false}, // 已取消
      { list: [], page: 1, len: 0, all: false} // 已结束
    ],
    size:8 // 每次请求数
  },
  onLoad() {
  },
  onShow() {
    this._getOrderList(0, true)
  },
  _getOrderList(type,state) {
    let arr = this.data.orderList[type]
    if (!arr.all || state) { // 判断是否为全部数据了，如果不是再请求
      getOrderList({ status: type, page: arr.page, length: this.data.size }).then(res => {
        let orders = res.data.orders
        if (res.code == 200) {
          this.setData({
            [`orderList[${type}].list`]: [...this.data.orderList[type], ...orders],
            [`orderList[${type}].len`]: arr.len + orders.length,
            [`orderList[${type}].all`]: !orders.length>0
          })
          if (orders.length > 0) {
            this.setData({
              [`orderList[${type}].page`]: Number(arr.page) + 1
            })
          }
        } else {
          this.setData({[`orderList[${type}].all`]: true})
        }
      })
    }
  },
  changeNav(type){ // 导航栏切换
    this.setData({ navIndex: type.currentTarget.dataset.type })
    this._getOrderList(type.currentTarget.dataset.type)
  },
  _cancelOrder(e){
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '确认要取消订单吗?',
      success(res) {
        if (res.confirm) {
          cancelOrder(e.currentTarget.dataset.id).then(res => {
            console.log(res)
            if(res.code==200){
              wx.showToast({
                title: '取消成功',
              })
              _this.setData({ ['orderList[' + _this.data.navIndex + '].list[' + e.currentTarget.dataset.index +'].status']:2}) // 退款成功改为已取消
            }
          })
        }
      }
    })
  },
  onReachBottom() {
    this._getOrderList(this.data.navIndex)
  },
  onPullDownRefresh() {
    this.onShow()
  }
})
